package judesart.app.service;

import javax.inject.Inject;

import judesart.app.domain.Role;
import judesart.app.domain.User;
import judesart.app.domain.UserRole;
import judesart.app.repository.UserDAO;
import judesart.app.shared.ValidationException;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("UserService")
public class UserServiceImpl implements UserService
{

    @Inject
    private UserDAO userDAO;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean createAdminUser() throws ValidationException
    {
        User admin = userDAO.findUserByUsername("admin");
        if (admin == null)
        {
            User user = new User();
            user.setUsername("admin");
            user.setPassword("admin");
            user.setName("Administrator");
            user.setEmail("admin@example.com");
            UserRole userRole = new UserRole();
            userRole.setUser(admin);
            userRole.setRole(Role.ROLE_ADMIN);
            user.addRole(userRole);
            admin = userDAO.createUser(user);
            return true;
        } else
        {
            return false;
        }
    }

    public User getCurrentUser()
    {
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal != null)
        {
            return userDAO.findUserByUsername(principal.getUsername());
        } else
        {
            return null;
        }
    }
}
